package core.proto.search;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JComponent;
import javax.swing.JTextField;

import prefuse.util.ColorLib;
import prefuse.util.ui.JSearchPanel;

/**
 * Acknowledgement: 
 * The painting logic is taken from {@link prefuse.util.ui.JSearchPanel}'s CancelButton class.  
 */
public class SearchCancelButton extends JComponent implements MouseListener {
	private static final long serialVersionUID = 1L;
	private boolean hover = false;
	private int[] outline = new int[] { 0, 0, 2, 0, 4, 2, 5, 2, 7,
			0, 9, 0, 9, 2, 7, 4, 7, 5, 9, 7, 9, 9, 7, 9, 5, 7, 4,
			7, 2, 9, 0, 9, 0, 7, 2, 5, 2, 4, 0, 2, 0, 0 };
	private int[] fill = new int[] { 1, 1, 8, 8, 1, 2, 7, 8, 2, 1,
			8, 7, 7, 1, 1, 7, 8, 2, 2, 8, 1, 8, 8, 1 };

	JTextField textField;
	public SearchCancelButton(JTextField textField){
		// set button size
		Dimension d = new Dimension(10, 10);
		this .setPreferredSize(d);
		this .setMinimumSize(d);
		this .setMaximumSize(d);
	
		this.textField = textField;
		// prevent the widget from getting the keyboard focus
		this .setFocusable(false);
		// add callback to handle hovers. 
		this.addMouseListener(this);
	}

	public void paintComponent(Graphics g) {
		if (hover) { // draw fill
			g.setColor(ColorLib.getColor(255, 75, 75));
			for (int i = 0; i + 3 < fill.length; i += 4) {
				g.drawLine(fill[i], fill[i + 1], fill[i + 2],
						fill[i + 3]);
			}
		}
		g.setColor(Color.black);
		
		for (int i = 0; i + 3 < outline.length; i += 2) {
			g.drawLine(outline[i], outline[i + 1], outline[i + 2],
					outline[i + 3]);
		}
	}

	public void mouseClicked(MouseEvent arg0) {
		textField.setText("");
	}

	public void mousePressed(MouseEvent arg0) {
	}

	public void mouseReleased(MouseEvent arg0) {
	}

	public void mouseEntered(MouseEvent arg0) {
		hover = true;
		repaint();
	}

	public void mouseExited(MouseEvent arg0) {
		hover = false;
		repaint();
	}

}
